<?php

namespace app\api\controller\shop;


use app\common\controller\Api;
use app\common\model\Category;
use app\common\model\Custom;
use app\common\model\Distribution;
use app\common\model\Shop;
use app\common\model\shop\Goods;
use app\common\model\shop\Order as ShopOrder;
use app\common\model\shop\Ordergoods;
use Express;
use think\Db;

/**
 * 商城订单
 * @ApiWeigh (90)
 */
class Order extends Api
{

    //如果$noNeedLogin为空表示所有接口都需要登录才能请求
    //如果$noNeedRight为空表示所有接口都需要验证权限才能请求
    //如果接口已经设置无需登录,那也就无需鉴权了
    //
    // 无需登录的接口,*表示全部
    protected $noNeedLogin = ['list'];
    // 无需鉴权的接口,*表示全部
    protected $noNeedRight = ['*'];

    /**
     * 配送方式
     * @Author xy
     * @ApiTitle 
     * @ApiMethod (POST)
     * @ApiReturnParams (name="code", type="integer", required=true, sample="0")
     * @ApiReturn ({'code':'0','msg':'返回成功'})
     */
    public function list()
    {
        $res = Distribution::where(['pid' => 0])->order('weigh desc')->select();
        $this->responseMsg(0, $res);
    }
    /**
     * 订单结算页
     * @Author xy
     * @ApiTitle 
     * @ApiMethod (POST)
     * @ApiParams (name="goods_info", type="json", required=true, description="[{'id':1,'num':1},...]//商品ID 数量")
     * @ApiParams (name="custom_id", type="int", required=true, description="客户ID")
     * @ApiParams (name="custom_id", type="int", required=true, description="客户ID")
     * @ApiParams (name="distribution_id", type="int", required=true, description="配送方式")
     */
    public function preorder()
    {
        $param = $this->request->post();
        extract($param);
        if (!isset($custom_id) || !$custom_id) {
            $this->error('请选择客户');
        }
        if (!isset($goods_info) || !$goods_info) {
            $this->error('请选择下单商品');
        }
        $custom = Custom::get($custom_id);
        if (!$custom) {
            $this->error('客户不存在');
        }
        $arr = ShopOrder::yuOrder(json_decode(htmlspecialchars_decode($goods_info), true), $distribution_id, $address_id ?? 0, $custom_id);

        $data = [
            'customInfo' => $custom,
            'goodsList' => $arr['goods_list'],
            'total_fee' => round($arr['total_fee'], 2),
            'pay_fee' => round($arr['pay_fee'], 2),
            'send_fee' => round($arr['send_fee'], 2),
            'total_money' => round($arr['total_money'], 2),
            'total_original_price' => round($arr['total_original_price'], 2),
        ];
        $this->success('', $data);
    }

    /**
     * 提交订单
     * @Author xy
     * @ApiTitle 
     * @ApiMethod (POST)
     * @ApiParams (name="goods_info", type="json", required=true, description="[{'id':1,'num':1,'pay_money':1},...]//商品ID 数量 单价")
     * @ApiParams (name="custom_id", type="int", required=true, description="客户ID")
     * @ApiParams (name="remark", type="string", required=true, description="备注")
     * @ApiParams (name="pay_image", type="string", required=true, description="付款凭证")
     * @ApiParams (name="distribution_id", type="int", required=true, description="配送方式")
     * @ApiParams (name="address_id", type="int", required=true, description="地址ID")
     * 
     * @ApiParams (name="orderid", type="int", required=true, description="订单ID")
     * 
     */
    public function addorder()
    {
        $user = $this->auth->getUser();
        $param = $this->request->post();
        extract($param);
        if (!isset($custom_id) || !$custom_id) {
            $this->error('请选择客户');
        }
        if (!isset($goods_info) || !$goods_info) {
            $this->error('请选择下单商品');
        }
        if (!isset($distribution_id) || !$distribution_id) {
            $this->error('请选择配送方式');
        }

        Db::startTrans();
        try {
            $data = ShopOrder::yuOrder(json_decode(htmlspecialchars_decode($goods_info), true), $distribution_id, $address_id ?? 0, $custom_id, 1);
            $order_id = ShopOrder::addOrder($custom_id, $address_id ?? 0, $user['id'], $data, $pay_image, $distribution_id, $remark ?? 'remark', $orderid ?? 0);
            Db::commit();
        } catch (\Exception $e) {
            Db::rollback();
            $this->error($e->getMessage());
        }
        $this->success('下单成功', compact('order_id'));
    }

    /**
     * 确认收货
     * @Author xy
     * @ApiTitle 
     * @ApiMethod (POST)
     * @ApiParams (name="id", type="int", required=true, description="订单ID")
     */
    public function confirmOrder()
    {
        $post = request()->post();
        extract($post);
        if (!isset($id) || !$id) {
            $this->error('参数错误');
        }
        $order = ShopOrder::get($id);
        if (!$order) {
            $this->error('订单不存在');
        }
        if ($order->status != '1') {
            $this->error('订单状态错误');
        }
        $order->finished_time = time();
        $order->status = '99';
        $res = $order->save();
        if ($res) {
            $this->success('收货成功');
        }
        $this->error('收货失败');
    }

    /**
     * 重新提交
     * @Author xy
     * @ApiTitle 
     * @ApiMethod (POST)
     * @ApiParams (name="id", type="int", required=true, description="订单ID")
     * @ApiParams (name="pay_image", type="int", required=true, description="付款凭证")
     * 
     */
    public function resubmit()
    {
        $post = request()->post();
        extract($post);
        if (!isset($id) || !$id) {
            $this->error('参数错误');
        }
        $order = ShopOrder::get($id);
        if (!$order) {
            $this->error('订单不存在');
        }
        if ($order->status != '-1' && $order->status != '-0.5') {
            $this->error('订单状态错误');
        }
        $order->pay_image = $pay_image;
        // $order->pay_time = time();
        $order->status = '0';
        $res = $order->save();
        if ($res) {
            $this->success();
        }
        $this->error('操作失败');
    }

    /**
     * 订单列表
     * @Author xy
     * @ApiTitle 
     * @ApiMethod (GET)
     * @ApiParams (name="keyword", type="string", required=true, description="搜索关键字")
     * @ApiParams (name="status", type="int", required=true, description="-0.5=待付款,0=待审核,0.5=备货中,1=运输中,99=成功")
     */
    public function order_list()
    {
        $user = $this->auth->getUser();
        $param = request()->param();
        extract($param);
        if (!isset($status)) {
            $this->error('参数错误');
        }
        $order_list = new ShopOrder();
        $order_list->alias('order')->where('order.user_id', $user->id);
        if ($status != 'all') {
            $order_list->where('order.status', $status);
        }

        if (isset($keyword) && $keyword) {
            $order_list->with(['incustom', 'ordergoods'])->where('incustom.name|incustom.phone', 'like', '%' . $keyword . '%');
            // $order_list->join('custom c', 'c.id = order.custom_id and (c.name like "%' . $keyword . '%" or c.phone like "%' . $keyword . '%")', 'INNER');
        } else {
            $order_list->with('ordergoods');
        }
        $list = $order_list->order('order.id desc')->paginate();
        $this->success('成功', $list);
    }

    /**
     * 订单详情
     * @Author xy
     * @ApiTitle 
     * @ApiMethod (GET)
     * @ApiParams (name="id", type="int", required=true, description="订单id")
     */
    public function order_info()
    {
        $param = request()->param();
        extract($param);
        if (!isset($id)) {
            $this->error('参数错误');
        }
        $data = ShopOrder::get($id, ['ordergoods', 'wl', 'distribution']);
        $this->responseMsg(0, $data);
    }

    /**
     * @Author LK
     * @ApiTitle (删除订单)
     * @ApiMethod (POST)
     * @ApiParams (name="id", type="integer", required=true, sample="", description="ID")
     * @ApiReturnParams (name="code", type="integer", required=true, description="")
     * @ApiReturn ({'code':1,'msg':'返回成功'})
     */
    public function del_order()
    {
        $param = request()->param();
        extract($param);
        if (!isset($id)  && !$id) {
            $this->error('参数错误');
        }
        $order = ShopOrder::get($id);
        if (!$order) {
            $this->error('订单不存在');
        }
        if ($order->status > 0) {
            $this->error('订单不可删除');
        }
        Db::startTrans();
        try {
            $order->delete();
            Ordergoods::where('order_id', $id)->delete();
            Db::commit();
        } catch (\Exception $e) {
            Db::rollback();
            $this->error('删除失败:' . $e->getMessage());
        }
        $this->success('删除成功');
    }

    /**
     * @Author LK
     * @date: 2023-10-23 
     * @ApiTitle (查看物流)
     * @ApiMethod (GET)
     * @ApiParams (name="id", type="integer", required=true, sample="", description="ID")
     * @ApiReturnParams (name="code", type="integer", required=true, description="")
     * @ApiReturn ({'code':1,'msg':'返回成功'})
     */
    public function logistics()
    {
        $param = request()->param();
        extract($param);
        if (!isset($id) || empty($id)) {
            $this->error('参数错误');
        }
        $order = ShopOrder::get($id);
        if (!$order) {
            $this->error('订单不存在');
        }
        $express_com = Category::where('id', $order['express_id'])->find();

        $express = new Express(['express_com' => $express_com->nickname ?? '', 'express_no' => $order->express_no ?? '', 'mobile' => $order->consign_mobile ?? '']);

        $wuliu = $express->getOrderTracesByJson();
        $wuliu['express_name'] = $express_com['name'] ?? "";
        $wuliu['address'] = $order['consign_address'];
        // $wuliu['city'] = $order['city'];
        $wuliu['nu'] = $order['express_no'];
        $this->success('', $wuliu);
    }
    /**
     * @Author LK
     * @date: 2025-04-23 17:01:08
     * @ApiTitle (上传物流凭证)
     * @ApiMethod (POST)
     * @ApiParams (name="id", type="integer", required=true, sample="", description="ID")
     * @ApiParams (name="express_images", type="string", required=true, sample="", description="关键字")
     * @ApiReturnParams (name="code", type="integer", required=true, description="")
     * @ApiReturn ({"code":0,"msg":"返回成功"})
     */
    public function express_images()
    {
        $param = request()->param();
        extract($param);
        if (!isset($id) || empty($id)) {
            $this->error('参数错误');
        }
        $order = ShopOrder::get($id);
        if (!$order) {
            $this->error('订单不存在');
        }
        if ($order['status'] != '-0.4') {
            $this->error('订单状态错误');
        }
        $order->express_images = $express_images;
        $order->status = 0;
        $res = $order->save();
        if (!$res) {
            $this->error('操作失败');
        }
        $this->success("提交成功");
    }
}
